package com.example.demospring.service.assistant;

import com.example.demospring.dto.assistant.ConsultingAppointmentWithAuditsDTO;
import com.example.demospring.entity.ConsultingAppointment;
import com.example.demospring.entity.ConsultingAppointmentAudit;
import com.example.demospring.repository.ConsultationCaseReportRepository;
import com.example.demospring.repository.ConsultingAppointmentAuditRepository;
import com.example.demospring.repository.ConsultingAppointmentRepository;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ConsultingService {

    @Autowired
    private ConsultingAppointmentRepository appointmentRepository;
    @Autowired
    private ConsultingAppointmentAuditRepository auditRepository;
    @Autowired
    private ConsultationCaseReportRepository caseReportRepository;

    /**
     * 查询某预约详情及audit记录（DTO封装）
     */
    public ConsultingAppointmentWithAuditsDTO getAppointmentWithAudits(Integer id) {
        ConsultingAppointment appointment = appointmentRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Appointment not found"));
        List<ConsultingAppointmentAudit> auditList = auditRepository.findByAppointmentId(id);

        ConsultingAppointmentWithAuditsDTO dto = new ConsultingAppointmentWithAuditsDTO();
        dto.setAppointment(appointment);
        dto.setAuditList(auditList);
        return dto;
    }

    /**
     * 删除咨询预约及所有相关审核记录，需事务保证一致性
     */
    @Transactional
    public void deleteAppointmentAndAudits(Integer id) {
        // 先删从表，再删主表
        auditRepository.deleteByAppointmentId(id);
        appointmentRepository.deleteById(id);
    }
    @Transactional
    public void deleteAppointmentAndAllRelated(Integer id) {
        // 1. 删除 case_reports 孙表
        caseReportRepository.deleteByAppointmentId(id);
        // 2. 删除 audit 从表
        auditRepository.deleteByAppointmentId(id);
        // 3. 删除主表
        appointmentRepository.deleteById(id);
    }
}
